﻿using System;
using System.Collections.Generic;
using System.Linq;
using Colligate;
using System.Data.Objects;

namespace OrgDataSource
{
// ReSharper disable InconsistentNaming
    public class CompanyDS:IOrgDS
// ReSharper restore InconsistentNaming
    {
        #region\\delete
        public int DeleteTaskData(OUDataInfo userInfo, string dataGuid, string dataType, orgEntities context)
        {
            switch (dataType.ToLower())
            {
                case "company": return DeleteCompany(dataGuid, context);
                default: throw new Exception("CompanyDS无法处理该" + dataType + "的数据");
            }
        }

        private static int DeleteCompany(string dataGuid, orgEntities context)
        {
            try
            {
                var company = context.Company.FirstOrDefault(cc => cc.Guid == dataGuid);
                context.DeleteObject(company);
                var result = context.SaveChanges();
                return result == 1 ? 0 : 1;
            }
            catch
            {
                throw new Exception("删除数据标识为：" + dataGuid + "的Company数据时出错！");
            }
           
        }
        #endregion
        #region\\get
        public System.Xml.XmlNode GetTaskData(OUDataInfo userInfo, string dataGuid, string dataType, orgEntities context, BaseTaskDataSource baseInfo)
        {
            switch (dataType.ToLower())
            {
                case "company": return GetCompany(dataGuid, context);
                case "companylist": return GetCompanyList(dataGuid, context);
                case "companyapplist": return GetCompanyAppList(dataGuid, context);
                case "companybranchs": return GetCompanyBranchs(dataGuid, context);
                default: EnvironmentInfo.WriteLogInfo("CompanyDS无法处理该" + dataType + "的数据", DebugLevel.CodePoint); return null;
            }
        }

        private static System.Xml.XmlNode GetCompany(string dataGuid, orgEntities context)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "Company");
                var company = context.Company.FirstOrDefault(cc => cc.Guid == dataGuid) ?? new Company
                                                                                               {
                                                                                                   Guid = string.Empty,
                                                                                                   Name = string.Empty,
                                                                                                   Domain = string.Empty,
                                                                                                   MasterGuid = null,
                                                                                                   EventerGuid = string.Empty,
                                                                                                   Telephone = string.Empty,
                                                                                                   EMail = string.Empty,
                                                                                                   MasterType = string.Empty,
                                                                                                   SubType = string.Empty,
                                                                                                   Sort = null
                                                                                               };
                XmlNodeManage.SetSubValue(result, "Guid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), company.Guid);
                XmlNodeManage.SetSubValue(result, "Name", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), company.Name);
                XmlNodeManage.SetSubValue(result, "Domain", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), company.Domain);
                XmlNodeManage.SetSubValue(result, "MasterGuid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), company.MasterGuid);
                XmlNodeManage.SetSubValue(result, "EventerGuid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), company.EventerGuid);
                XmlNodeManage.SetSubValue(result, "Telephone", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), company.Telephone);
                XmlNodeManage.SetSubValue(result, "EMail", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), company.EMail);
                XmlNodeManage.SetSubValue(result, "MasterType", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), company.MasterType);
                XmlNodeManage.SetSubValue(result, "SubType", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), company.SubType);
                XmlNodeManage.SetSubValue(result, "Order", Enum.GetName(typeof(TypeEnum), TypeEnum.LONG), company.Sort);
                return result;
            }
            catch
            {
                throw new Exception("获取数据标识为：" + dataGuid + "的Company数据时出错！");
            }
        }
        private static System.Xml.XmlNode GetCompanyList(string dataGuid, orgEntities context)
        {
            try
            {
                if (dataGuid != "9ab2e46a-5371-4daf-b9d0-f175243a45d6")
                    throw new Exception("数据标识不正确！");
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "CompanyList");
                var cloneList = new Company[context.Company.Count()] ;
                context.Company.ToList().CopyTo(cloneList);
                ObjectQuery<System.Data.Common.DbDataRecord> query = context.Company.GroupBy("it.MasterType,it.SubType", "it.MasterType,it.SubType");
                foreach (var r in query)
                {
                    var masterType = r["MasterType"].ToString();
                    var subType = r["SubType"].ToString();
                    var subNode = XmlNodeManage.CreateNode("ListOUDataInfo");
                    XmlNodeManage.SetSubValue(subNode, "@MasterType", masterType);
                    XmlNodeManage.SetSubValue(subNode, "@SubType", subType);
                    var temp = cloneList.Where(cc => cc.MasterType == masterType && cc.SubType == subType);
                    foreach (var item in temp)
                    {
                        var childNode = XmlNodeManage.CreateNode("OUDataInfo");
                        XmlNodeManage.SetSubValue(childNode, "@GUID", item.Guid);
                        XmlNodeManage.SetSubValue(childNode, "@NAME", item.Name);
                        XmlNodeManage.SetSubValue(childNode, "@OUType", "Company");
                        XmlNodeManage.SetSubValue(childNode, "@CompanyGuid", item.Guid);
                        subNode.AppendChild(childNode);
                    }
                    result.AppendChild(subNode);
                }
                return result;
            }
            catch
            {
                throw new Exception("获取的CompanyList数据时出错！");
            }
        }
        private static System.Xml.XmlNode GetCompanyAppList(string dataGuid, orgEntities context)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "CompanyAppList");
                var application = context.Application.Where(cc => cc.CompanyGuid == dataGuid);
                foreach (var item in application)
                {
                    var subNode = XmlNodeManage.CreateNode("Application");
                    XmlNodeManage.SetSubValue(subNode, "Guid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.Guid);
                    XmlNodeManage.SetSubValue(subNode, "Name", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.Name);
                    XmlNodeManage.SetSubValue(subNode, "IPAddress", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.IPAddress);
                    XmlNodeManage.SetSubValue(subNode, "Protocol", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.Protocol);
                    XmlNodeManage.SetSubValue(subNode, "CompanyGuid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.CompanyGuid);
                    XmlNodeManage.SetSubValue(subNode, "CompanyName", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.CompanyName);
                    XmlNodeManage.SetSubValue(subNode, "Admin", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.Admin);
                    XmlNodeManage.SetSubValue(subNode, "Telephone", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.Telephone);
                    XmlNodeManage.SetSubValue(subNode, "EMail", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.EMail);
                    XmlNodeManage.SetSubValue(subNode, "MasterType", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.MasterType);
                    XmlNodeManage.SetSubValue(subNode, "SubType", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), item.SubType);
                    result.AppendChild(subNode);
                }
                return result;
            }
            catch
            {
                throw new Exception("获取的MemberGroupList数据时出错！");
            }
        }
        private static System.Xml.XmlNode GetCompanyBranchs(string dataGuid, orgEntities context)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "CompanyBranchs");
                var subNode = XmlNodeManage.CreateNode("ListOUDataInfo");
                var branch = context.Branch.Where(cc => cc.CompanyGuid == dataGuid).OrderByDescending(cc=>cc.Sort).ToList();
                foreach (var item in branch)
                {
                    var childNode = XmlNodeManage.CreateNode("OUDataInfo");
                    XmlNodeManage.SetSubValue(childNode, "@GUID", item.Guid);
                    XmlNodeManage.SetSubValue(childNode, "@NAME", GetBranchPath(item, branch, string.Empty));
                    XmlNodeManage.SetSubValue(childNode, "@OUType", "Branch");
                    XmlNodeManage.SetSubValue(childNode, "@CompanyGuid", item.CompanyGuid);
                    subNode.AppendChild(childNode);
                }
                result.AppendChild(subNode);
                return result;
            }
            catch
            {
                throw new Exception("获取的BranchList数据时出错！");
            }
        }

        #endregion
        #region\\set
        public int SetTaskData(OUDataInfo userInfo, string dataGuid, string dataType, System.Xml.XmlNode xmlData, orgEntities context)
        {
            var datatype = XmlNodeManage.GetSubValue(xmlData, "@DataType");
            switch (datatype.ToLower())
            {
                case "company": return SetCompany(xmlData, context);
                default: EnvironmentInfo.WriteLogInfo("CompanyTask无法处理该" + datatype + "的数据", DebugLevel.CodePoint); return 1;
            }
        }

        private static int SetCompany(System.Xml.XmlNode xmlData, orgEntities context) 
        {
            try
            {
                var id = Utility.CheckXmlData(xmlData,"Guid");
                var company=context.Company.FirstOrDefault(cc => cc.Guid == id);
                if (null == company)
                {
                    company = new Company
                                  {
                                      Guid = id,
                                      Domain = Utility.CheckXmlData(xmlData, "Domain"),
                                      EMail = Utility.CheckXmlData(xmlData, "EMail"),
                                      EventerGuid = Utility.CheckXmlData(xmlData, "EventerGuid"),
                                      MasterGuid = Utility.CheckXmlData(xmlData, "MasterGuid"),
                                      MasterType = Utility.CheckXmlData(xmlData, "MasterType"),
                                      Name = Utility.CheckXmlData(xmlData, "Name"),
                                      Telephone = Utility.CheckXmlData(xmlData, "Telephone"),
                                      Sort = int.Parse(Utility.CheckXmlData(xmlData, "Order")),
                                      SubType = Utility.CheckXmlData(xmlData, "SubType")
                                  };
                    context.AddToCompany(company);
                }
                else
                {
                    company.Domain = Utility.CheckXmlData(xmlData, "Domain");
                    company.EMail = Utility.CheckXmlData(xmlData, "EMail");
                    company.EventerGuid = Utility.CheckXmlData(xmlData, "EventerGuid");
                    company.MasterGuid = Utility.CheckXmlData(xmlData, "MasterGuid");
                    company.MasterType = Utility.CheckXmlData(xmlData, "MasterType");
                    company.Name = Utility.CheckXmlData(xmlData, "Name");
                    company.Telephone = Utility.CheckXmlData(xmlData, "Telephone");
                    company.Sort = int.Parse(Utility.CheckXmlData(xmlData, "Order"));
                    company.SubType = Utility.CheckXmlData(xmlData, "SubType");
                }
                var result = context.SaveChanges();
                return result == 1 ? 0 : 1;
            }
            catch
            {
                throw new Exception("写入Company数据时出错！");
            }
        }
        #endregion
        #region\\transform
        public System.Xml.XmlNode TransformTaskData(OUDataInfo userInfo, System.Xml.XmlNode xmlParam, orgEntities context, BaseTaskDataSource baseInfo)
        {
            return null;
        }
        #endregion
        private static string GetBranchPath(Branch branch, IEnumerable<Branch> list, string result)
        {
            if (null == branch)
                return result.Trim('→');
            if (branch.ParentGuid != branch.CompanyGuid)
            {
                result = "→" + branch.Name + result;
                return GetBranchPath(list.FirstOrDefault(cc => cc.Guid == branch.ParentGuid), list, result);
            }
            return result + branch.Name;
        }
    }
}
